package com.bf.xpdd.web.controller.account;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.bf.xpdd.config.ConfigParameter;
import com.bf.xpdd.domain.SiteBuyer;
import com.bf.xpdd.domain.SiteSeller;
import com.bf.xpdd.domain.SiteShop;
import com.bf.xpdd.exception.BaseException;
import com.bf.xpdd.exception.EncryptException;
import com.bf.xpdd.service.AccountService;
import com.bf.xpdd.service.TaobaoService;
import com.bf.xpdd.util.JSONTranslator;
import com.bf.xpdd.util.TaobaoEncrypt;

/**
 * User information
 * 
 * @author Fantastic
 * @version 1.0.0 2011-05-31
 * @since 1.0.0
 */
@Controller
public class UserController
{
	/** logger */
	private static final Logger log = Logger.getLogger(UserController.class);

	/** account service */
	@Autowired
	private AccountService accountService;

	/** taobao service */
	@Autowired
	private TaobaoService taobaoService;

	/**
	 * default page
	 * 
	 * @return page
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping(value = "/admin", method = RequestMethod.GET)
	public String showBackDefault(HttpServletRequest request, HttpServletResponse response) throws IOException,
			ServletException
	{
		// http://callback.com/callback?top_appkey=xxx&top_parameters=xxxxx&top_session=xxxxx&top_sign=xxxxx

		// 如果是后台用户（商家），检查入库
		String appkey = request.getParameter("top_appkey");
		if (null != appkey && appkey.equals(ConfigParameter.BACK_APPKEY))
		{
			// 组装商家参数
			SiteSeller seller = new SiteSeller();
			seller.setNick(TaobaoEncrypt.ParametersName(request.getParameter("top_parameters")));
			seller.setTopParameter(request.getParameter("top_parameters"));
			seller.setTopSession(request.getParameter("top_session"));
			seller.setTopSign(request.getParameter("top_sign"));

			// 验证请求信息合法
			String topAppKey = request.getParameter("top_appkey");
			boolean isValid = false;
			try
			{
				isValid = TaobaoEncrypt.validateSign(seller.getTopSign(),
						topAppKey + seller.getTopParameter() + seller.getTopSession(), ConfigParameter.BACK_APP_SECRET);
			}
			catch (EncryptException e)
			{
				request.setAttribute("error", "非法的请求参数");
				return "error";
			}

			// 如果sessionKey不合法
			if (!isValid)
			{
				request.setAttribute("error", "非法的请求参数");
				return "error";
			}

			// TODO 检查、更新充值信息
			// http://my.open.taobao.com/apidoc/index.htm#categoryId:8-dataStructId:10312

			// 检查入库
			try
			{
				this.accountService.addNewSeller(seller, this.taobaoService);
				this.accountService.persistSession(seller);
			}
			catch (BaseException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			request.getSession().setAttribute("seller", seller);
		}

		// request.getRequestDispatcher("activity").forward(request, response);
		return "index";
	}

	/**
	 * default page
	 * 
	 * @return page
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping(value = "/show", method = RequestMethod.GET)
	public String showFrontDefault(HttpServletRequest request, HttpServletResponse response)
	{
		String topParameters = request.getParameter("top_parameters");
		if (null == topParameters || "".equals(topParameters))
		{
			request.setAttribute("error", "请登录淘宝网");
			return "front/front_error";
		}

		// 如果是后台用户（商家），检查入库
		String appkey = request.getParameter("top_appkey");
		SiteShop shop = new SiteShop();
		SiteBuyer buyer = new SiteBuyer();
		if (appkey.equals(ConfigParameter.FRONT_APPKEY))
		{
			// 组装商家参数--前台用
			String sellerNick = request.getParameter("seller_nick");
			SiteSeller seller = new SiteSeller();
			seller.setNick(sellerNick);
			try
			{
				this.taobaoService.findUserByNick(seller);
			}
			catch (BaseException e)
			{
				if ("-1".equals(e.getCode()))
				{
					try
					{
						sellerNick = new String(sellerNick.getBytes("ISO-8859-1"), "UTF-8");
					}
					catch (UnsupportedEncodingException e1)
					{
						request.setAttribute("error", "非法的请求参数");
						return "front/front_error";
					}
				}
			}

			// 保存参数
			shop.setSellerNick(sellerNick);
			shop.setIdShop(Long.parseLong(request.getParameter("shop_id").toString()));

			// 组装买家参数
			buyer.setNick(TaobaoEncrypt.ParametersName(topParameters));
			buyer.setTopParameter(request.getParameter("top_parameters"));
			buyer.setTopSession(request.getParameter("top_session"));
			buyer.setTopSign(request.getParameter("top_sign"));

			// 验证请求信息
			String topAppKey = request.getParameter("top_appkey");
			boolean isValid = false;
			try
			{
				isValid = TaobaoEncrypt.validateSign(buyer.getTopSign(),
						topAppKey + buyer.getTopParameter() + buyer.getTopSession(), ConfigParameter.FRONT_APP_SECRET);
			}
			catch (EncryptException e)
			{
				request.setAttribute("error", "非法的请求参数");
				return "front/front_error";
			}

			// 如果sessionKey不合法
			if (!isValid)
			{
				request.setAttribute("error", "请登录淘宝网");
				return "front/front_error";
			}

		}

		// 由于界面渲染后再提交请求，session会产生一个新的
		request.setAttribute("shop", com.bf.xpdd.util.Base64.encode(JSONTranslator.toJSON(shop, "utf-8", "utf-8")));
		request.setAttribute("buyer", com.bf.xpdd.util.Base64.encode(JSONTranslator.toJSON(buyer, "utf-8", "utf-8")));
		return "front/front_item";
	}

	/**
	 * default page
	 * 
	 * @return page
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request, HttpServletResponse response)
	{
		request.getSession().invalidate();
		
		try
		{
			response.sendRedirect(getlogoffURL());
			return "error";
		}
		catch (Exception e)
		{
			request.setAttribute("error", "出错啦。");
			return "error";
		}
	}

	/**
	 * 退出TOP登陆（清除top cookie）
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private String logoffopenid() throws UnsupportedEncodingException
	{
		TreeMap<String, String> apiparamsMap = new TreeMap<String, String>();

		// 组装协议参数。
		apiparamsMap.put("sign_method", "md5");
		apiparamsMap.put("app_key", ConfigParameter.BACK_APPKEY);
		apiparamsMap.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		String sign = TaobaoEncrypt.sign(apiparamsMap, ConfigParameter.BACK_APP_SECRET);
		// 组装协议参数sign
		apiparamsMap.put("sign", sign);
		StringBuilder param = new StringBuilder();
		for (Iterator<Map.Entry<String, String>> it = apiparamsMap.entrySet().iterator(); it.hasNext();)
		{
			Map.Entry<String, String> e = it.next();
			param.append("&").append(e.getKey()).append("=").append(e.getValue());
		}
		return param.toString().substring(1);
	}

	/*
	 * 获取app退出URL
	 */
	public String getlogoffURL() throws UnsupportedEncodingException
	{
		// 组装请求URL
		StringBuilder url = new StringBuilder(ConfigParameter.LOGOFF_URL + "?");
		url.append(logoffopenid());
		return url.toString();
	}

}
